package com.macro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.macro.enums.AppHttpCodeEnum;
import com.macro.mapper.UserLoginMapper;
import com.macro.mapper.UserMapper;
import com.macro.pojos.dto.LoginDto;
import com.macro.pojos.dto.ResponseResult;
import com.macro.pojos.pojo.Login;
import com.macro.pojos.pojo.User;
import com.macro.service.UserLoginService;
import com.macro.utils.AppJwtUtil;
import com.macro.utils.MD5Utils;
import com.macro.utils.SendSMSUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    UserLoginMapper userLoginMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /*
     * 用户登录
     * */
    @Override
    public ResponseResult UserLogin(LoginDto loginDto) {
        //参数校验
        if (loginDto.getPassword().equals("") || loginDto.getPhone().equals("")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "号码或密码不能为空");
        }
        //根据号码查询用户信息
        if (loginDto.getPhone() != null) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getTel, loginDto.getPhone());
            List<User> userList = userMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtils.isEmpty(userList)) {
                //数据为空
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "该号码的用户不存在");
            }
            if (userList.size() > 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL, "数据错误");
            }
            User user = userList.get(0);
            //对密码进行加密
            String password = MD5Utils.encodeWithSalt(loginDto.getPassword(), user.getSalt());
            //根据密码进行查询
            if (password.equals(user.getPassword())) {
                //验证码校验
                //从redis获取验证码
                Integer code = (Integer) redisTemplate.boundValueOps(loginDto.getPhone() + "的验证码为：").get();
                if (code == null) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "请输入验证码");
                }
                if (loginDto.getVcode().equals(code)) {
                    //验证码匹配，登陆成功
                    Map<String, Object> map = new HashMap<>();
                    user.setPassword("");
                    user.setSalt("");
                    map.put("password", password);
                    map.put("token", AppJwtUtil.getToken(Long.valueOf(user.getId())));
                    //删除redis缓存的验证码
                    redisTemplate.delete(loginDto.getPhone());
                    //存入登录日志表
                    Login login = new Login();
                    BeanUtils.copyProperties(loginDto, login);
                    login.setUserId(user.getId());
                    login.setEmail(user.getMailbox());
                    login.setNickname(user.getNickname());
                    login.setIsDelete(false);
                    login.setLoginName(user.getUsername());
                    login.setLoginTime(new Date());
                    login.setRegisterTime(user.getRegisterTime());
                    login.setVCode(loginDto.getVcode());
                    userLoginMapper.insert(login);
                    return ResponseResult.okResult(login);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.FAIL, "验证码错误");
                }
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAIL, "用户名或密码错误，登录失败");
    }

    /*
     * 发送验证码
     * */
    @Override
    public ResponseResult sendSms(String phoneNumber) {
        //phonenumber:15003739761
        //发送验证码
//        String result = SendSMSUtil.sendSmsUtil(phoneNumber);
//        //校验
//        if (result==null || !result.equals("ok")){
//            System.out.println(result);
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"验证码发送失败");
//        }
//        //获取验证码
//        String code = String.valueOf(SendSMSUtil.getCode());
//        //存入redis中
//        redisTemplate.boundValueOps(phoneNumber).set(code);
//        //设置过期时间(5分钟内有效)
////        redisTemplate.expire(phoneNumber,60*5, TimeUnit.MINUTES);
//        System.out.println(code);
//        return ResponseResult.okResult("验证码发送成功!5分钟内有效");
        //生成验证码
        Integer code = (int) ((Math.random() * 9 + 1) * 100000);
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        String smsUtil = SendSMSUtil.sendSmsUtil(phoneNumber);
        System.out.println(code);
        //如果发送成功，存入redis
        if (smsUtil != null) {
            redisTemplate.boundValueOps(phoneNumber+"的验证码为：").set(code);
            //设置有效时间
            //redisTemplate.expire(phoneNumber,5,TimeUnit.MINUTES);
            return ResponseResult.okResult(phoneNumber + "验证码为：" + code);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL, "验证码发送失败");
        }
    }
}
